import * as apis from 'services/gallery'
import * as types from '../mutation-types'

const state = {
  list: {
    data: [],
    total: 0,
  },
  groupList: [],
}

const actions = {
  async getImageList({ commit }, { pageSize = 20, page = 1, gid = 0 }) {
    const res = await apis.getImageList({ pageSize, page, gid })
    const data = await res.data
    commit(types.GET_IMG_LIST_SUCCESS, data)
  },

  async deleteImgById({ commit }, id) {
    const res = await apis.deleteImgById(id)
    commit(types.DELETE_IMG_SUCCESS, id)
    return res
  },

  async getGroupList({ commit }) {
    const res = await apis.getGroupList()
    commit(types.GET_GROUP_LIST_SUCCESS, res.data)
  },

  async imageGrouping({ commit }, { id, gid }) {
    commit(types.IMAGE_GROUPING, { id, gid })
    const res = await apis.imageGrouping({ id, gid })
    return res
  },
}

const mutations = {
  [types.GET_IMG_LIST_SUCCESS](state, data) {
    state.list = {
      data: data.data,
      total: data.total,
    }
  },

  [types.DELETE_IMG_SUCCESS](state, id) {
    state.list.data = state.list.data
      .filter(item => item.id !== id)
  },

  [types.GET_GROUP_LIST_SUCCESS](state, data) {
    const ret = data
    ret.unshift({
      id: 0,
      name: '未分组',
      status: 1,
    })
    state.groupList = ret
  },

  [types.IMAGE_GROUPING](state, { id, gid }) {
    state.list.data = state.list.data.map((item) => {
      if (item.id === id) {
        item.gid = gid
      }
      return item
    })
  },
}

export default {
  state,
  actions,
  mutations,
}
